<template>
  <div class="space-y-4" ref="messageListRef">
    <ChatBubble 
      v-for="message in messages" 
      :key="message.id"
      :mine="message.type === 'user'"
      :avatar="message.type === 'user' ? userAvatar : roleAvatar"
      :isTyping="message.isTyping"
      :class="{ 'error-message': message.isError }"
    >
      {{ message.content }}
      <template v-if="message.type === 'assistant'">
        <!-- 错误消息重试按钮 -->
        <div v-if="message.isError" class="mt-3 flex items-center gap-2">
          <!-- <button 
            @click="retryMessage(message.id)"
            class="px-3 py-1.5 text-xs bg-red-50 text-red-600 rounded-lg hover:bg-red-100 transition-colors flex items-center gap-1"
          >
            <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            重试
          </button> -->
        </div>
        <div v-if="message.imageLoading" class="mt-2 text-xs text-gray-500 flex items-center gap-2">
          <svg class="animate-spin h-4 w-4 text-gray-400" viewBox="0 0 24 24">
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/>
            <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
          </svg>
          图片生成中...
        </div>
        <div v-if="message.images && message.images.length" class="mt-2 grid grid-cols-2 gap-2">
          <a v-for="(img, idx) in message.images" :key="idx" :href="img" target="_blank" rel="noreferrer" class="block">
            <img :src="img" class="w-full h-auto rounded-lg border border-gray-200" />
          </a>
        </div>
      </template>
    </ChatBubble>
    
    <!-- 空状态 -->
    <div v-if="messages.length === 0" class="empty-state">
      <div class="empty-icon">💬</div>
      <div class="empty-text">开始与{{ roleName }}对话吧！</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from 'vue'
import ChatBubble from './ChatBubble.vue'
import type { ChatMessage } from '@/api/interface'

interface Props {
  roleName: string
  roleAvatar: string
}

withDefaults(defineProps<Props>(), {
  roleName: 'AI助手',
  roleAvatar: 'https://picsum.photos/seed/ai/80/80'
})

const emit = defineEmits<{
  (e: 'retry', messageId: string): void
}>()

const messages = ref<ChatMessage[]>([])
const messageListRef = ref<HTMLElement>()
const currentTypingMessageId = ref<string | null>(null)
const userAvatar = 'https://picsum.photos/seed/user/80/80'

// 生成唯一 id
const genId = (prefix: string) => `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 8)}`

// 添加用户消息（可指定 id）
const addUserMessage = (content: string, id?: string) => {
  const message: ChatMessage = {
    id: id || genId('user'),
    type: 'user',
    content: content,
    timestamp: Date.now(),
    isTyping: false
  }
  messages.value.push(message)
  scrollToBottom()
}

// 开始AI回复（打字机效果）
const startAIResponse = () => {
  const messageId = genId('assistant')
  const message: ChatMessage = {
    id: messageId,
    type: 'assistant',
    content: '',
    timestamp: Date.now(),
    isTyping: true
  }
  messages.value.push(message)
  currentTypingMessageId.value = messageId
  scrollToBottom()
  return messageId
}

// 更新AI回复内容
const updateAIMessage = (content: string) => {
  if (currentTypingMessageId.value) {
    const message = messages.value.find(m => m.id === currentTypingMessageId.value)
    if (message) {
      message.content = content
    }
  }
  scrollToBottom()
}

// 追加AI回复内容（流式）
const appendAIMessage = (chunk: string) => {
  if (currentTypingMessageId.value) {
    const message = messages.value.find(m => m.id === currentTypingMessageId.value)
    if (message) {
      message.content = (message.content || '') + chunk
    }
  }
  // 在打字机效果期间，使用 requestAnimationFrame 确保平滑滚动
  requestAnimationFrame(() => {
    scrollToBottom()
  })
}

// 完成AI回复
const completeAIMessage = (content: string) => {
  if (currentTypingMessageId.value) {
    const message = messages.value.find(m => m.id === currentTypingMessageId.value)
    if (message) {
      message.content = content
      message.isTyping = false
    }
    currentTypingMessageId.value = null
  }
  scrollToBottom()
}

// 显示错误消息
const showErrorMessage = (errorText: string = '抱歉，服务暂时不可用，请稍后重试') => {
  if (currentTypingMessageId.value) {
    const message = messages.value.find(m => m.id === currentTypingMessageId.value)
    if (message) {
      message.isTyping = false
      message.content = errorText
      message.isError = true
    }
    currentTypingMessageId.value = null
  } else {
    // 如果没有正在输入的消息，创建一个错误消息
    const messageId = genId('error')
    const message: ChatMessage = {
      id: messageId,
      type: 'assistant',
      content: errorText,
      timestamp: Date.now(),
      isTyping: false,
      isError: true
    }
    messages.value.push(message)
  }
  scrollToBottom()
}

// 重试消息
const retryMessage = (messageId: string) => {
  const message = messages.value.find(m => m.id === messageId)
  if (message && message.isError) {
    // 移除错误消息
    const index = messages.value.findIndex(m => m.id === messageId)
    if (index > -1) {
      messages.value.splice(index, 1)
    }
    // 触发重试事件
    emit('retry', messageId)
  }
}

// 获取最后一条用户消息
const getLastUserMessage = () => {
  for (let i = messages.value.length - 1; i >= 0; i--) {
    if (messages.value[i].type === 'user') {
      return messages.value[i]
    }
  }
  return null
}

// 直接追加一条助手完整消息（用于渲染历史）
const addAssistantFinalMessage = (content: string, id?: string, images?: string[], imageUrl?: string | null) => {
  // 处理单个图片URL，如果有imageUrl且不为null，则添加到images数组中
  const finalImages = images || []
  if (imageUrl && imageUrl.trim() !== '') {
    finalImages.push(imageUrl)
  }
  
  const message: ChatMessage = {
    id: id || genId('assistant'),
    type: 'assistant',
    content,
    timestamp: Date.now(),
    isTyping: false,
    images: finalImages
  }
  messages.value.push(message)
  scrollToBottom()
  return message.id
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    // 查找真正的滚动容器（带有 data-scroll-container 属性的父元素）
    const scrollContainer = document.querySelector('[data-scroll-container]')
    if (scrollContainer) {
      // 使用平滑滚动
      scrollContainer.scrollTo({
        top: scrollContainer.scrollHeight,
        behavior: 'smooth'
      })
    } else if (messageListRef.value) {
      // 备用方案：如果找不到滚动容器，尝试滚动消息列表本身
      messageListRef.value.scrollTo({
        top: messageListRef.value.scrollHeight,
        behavior: 'smooth'
      })
    }
  })
}

// 强制滚动到底部（用于图片加载等特殊情况）
const forceScrollToBottom = () => {
  nextTick(() => {
    const scrollContainer = document.querySelector('[data-scroll-container]')
    if (scrollContainer) {
      // 强制立即滚动，不使用平滑效果
      scrollContainer.scrollTop = scrollContainer.scrollHeight
    } else if (messageListRef.value) {
      messageListRef.value.scrollTop = messageListRef.value.scrollHeight
    }
  })
}

// 清空消息
const clearMessages = () => {
  messages.value = []
  currentTypingMessageId.value = null
}

// 暴露方法给父组件
defineExpose({
  addUserMessage,
  startAIResponse,
  updateAIMessage,
  appendAIMessage,
  completeAIMessage,
  addAssistantFinalMessage,
  showErrorMessage,
  getLastUserMessage,
  clearMessages,
  // 显式控制当前助手消息的图片占位与图片列表
  setCurrentMessageImageLoading: (loading: boolean) => {
    if (currentTypingMessageId.value) {
      const msg = messages.value.find(m => m.id === currentTypingMessageId.value)
      if (msg) {
        ;(msg as any).imageLoading = loading
      }
    }
    // 图片加载状态变化时也要滚动
    scrollToBottom()
  },
  setCurrentMessageImages: (imgs: string[]) => {
    if (currentTypingMessageId.value) {
      const msg = messages.value.find(m => m.id === currentTypingMessageId.value)
      if (msg) {
        ;(msg as any).images = imgs || []
        ;(msg as any).imageLoading = false
      }
    }
    // 图片加载完成时立即滚动
    forceScrollToBottom()
    
    // 延迟滚动，确保图片渲染完成
    setTimeout(() => {
      forceScrollToBottom()
    }, 200)
    
    // 额外延迟滚动，确保图片完全加载
    setTimeout(() => {
      forceScrollToBottom()
    }, 800)
  }
})
</script>

<style scoped>
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6b7280;
  padding: 3rem 0;
}

.empty-icon {
  font-size: 2.25rem;
  margin-bottom: 0.5rem;
}

.empty-text {
  font-size: 0.875rem;
}

/* 错误消息样式 */
:deep(.error-message) {
  background-color: #fef2f2 !important;
  border-color: #fecaca !important;
}

:deep(.error-message .chat-bubble) {
  background-color: #fef2f2 !important;
  border-color: #fecaca !important;
  color: #dc2626 !important;
}
</style>


